#!/usr/bin/python
# -*- coding: utf8 -*-

import sys
import base64
from Crypto.Cipher import AES

# ref: http://stackoverflow.com/a/12525165

#private static final String KEY_ALGORITHM = "AES";  //密钥加密算法
#private static final String AESTYPE = "AES/ECB/PKCS5Padding";

class AESCipher:

    BS = 16

    def __init__(self):
        self.key = 'ecdYo3MfA4wgxO6N'
        self.cipher = AES.new(self.key, AES.MODE_ECB)

    def encrypt(self, raw):
        raw = raw + (AESCipher.BS - len(raw) % AESCipher.BS) * chr(AESCipher.BS - len(raw) % AESCipher.BS) 
        return base64.b64encode(self.cipher.encrypt(raw)) 

    def decrypt(self, code):
        code = base64.b64decode(code)
        raw = self.cipher.decrypt(code)
        return raw[0:-ord(raw[-1])]




if __name__ == '__main__':
    if len(sys.argv) != 3:
        sys.exit("wrong argument number")

    method = sys.argv[1]
    text = sys.argv[2]
    encryptor = AESCipher()
    if 'enc' == method or 'e' == method:
        print encryptor.encrypt(text)
    elif 'dec' == method or 'd' == method:
        print encryptor.decrypt(text)
    else:
        print 'first argument, e for encrypt, d for decrypt'

